package com.photopicker.main.fragment;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.photopicker.R;
import com.photopicker.customview.FlowIndicator;
import com.photopicker.customview.Info;
import com.photopicker.customview.PhotoView;
import com.photopicker.util.Utils;


import java.util.ArrayList;


public class ImageBrowseDialogFragment extends DialogFragment {

    private ViewPager viewPager;
    private FlowIndicator indicator;
    private ArrayList<String> imageUrls;
    private Info info;
    private ArrayList<Info> infos;
    private View mask;//background view
    private int position;
    private boolean isExit = false;
    private boolean isFile = false;

    public static ImageBrowseDialogFragment newInstance(ArrayList<String> imageUrls, Info info, int position) {
        return newInstance(imageUrls, info, null, position);
    }

    public static ImageBrowseDialogFragment newInstance(ArrayList<String> imageUrls, Info info, ArrayList<Info> infos, int position) {
        return newInstance(imageUrls, info, infos, position, false);
    }

    public static ImageBrowseDialogFragment newInstance(ArrayList<String> imageUrls, Info info, ArrayList<Info> infos, int position, boolean isFile) {
        Bundle bundle = new Bundle();
        bundle.putStringArrayList(Info.INTENT_IMAGE_URLS, imageUrls);
        bundle.putParcelable(Info.INTENT_CLICK_IMAGE_INFO, info);
        bundle.putInt(Info.INTENT_CLICK_IMAGE_POSITION, position);
        bundle.putBoolean("isFile", isFile);
        if (infos != null) {
            bundle.putParcelableArrayList(Info.INTENT_IMAGE_INFOS, infos);
        }
        ImageBrowseDialogFragment fragment = new ImageBrowseDialogFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        return dialog;
    }

    @Override
    public void onResume() {
        super.onResume();
        Window window = getDialog().getWindow();
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_viewpager, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mask = view.findViewById(R.id.master);
        viewPager = (ViewPager) view.findViewById(R.id.viewpager);
        indicator = (FlowIndicator) view.findViewById(R.id.indicator);
        runEnterAnimation();
        Bundle bundle = getArguments();
        imageUrls = bundle.getStringArrayList(Info.INTENT_IMAGE_URLS);
        info = bundle.getParcelable(Info.INTENT_CLICK_IMAGE_INFO);
        infos = bundle.getParcelableArrayList(Info.INTENT_IMAGE_INFOS);
        position = bundle.getInt(Info.INTENT_CLICK_IMAGE_POSITION, 0);
        isFile = bundle.getBoolean("isFile", false);
        indicator.setCount(imageUrls.size());
        indicator.setVisibility(View.VISIBLE);

        PagerAdapter vpgPagerAdapter = isFile ? new BrowseVpgFromFileAdapter() : new BrowseVpgFromNetAdapter();

        viewPager.setAdapter(vpgPagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                indicator.setSelection(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        //set current position
        viewPager.setCurrentItem(position);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            exitFragment(v);
        }
    };

    private void exitFragment(View v) {
        if (infos == null) {
            dismissAllowingStateLoss();
        } else {
            //退出时点击的位置
            int position = (int) v.getTag();
            //回到上个界面该view的位置
            if (((FrameLayout) v.getParent()).getChildAt(1).getVisibility() == View.VISIBLE) {
                dismissAllowingStateLoss();
            } else {
                runExitAnimation(v);
                ((PhotoView) v).animateTo(infos.get(position), new Runnable() {
                    @Override
                    public void run() {
                        dismissAllowingStateLoss();
                    }
                });
            }
        }
    }

    private View.OnKeyListener pressKeyListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {//只监听返回键
                if (event.getAction() != KeyEvent.ACTION_UP) {
                    return true;
                }
                if (!isExit) {
                    isExit = true;
                    exitFragment(v);
                }
                return true;
            }
            return false;
        }
    };

    private void runEnterAnimation() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        alphaAnimation.setDuration(300);
        alphaAnimation.setInterpolator(new AccelerateInterpolator());
        mask.startAnimation(alphaAnimation);
    }

    public void runExitAnimation(final View view) {
        AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
        alphaAnimation.setDuration(300);
        alphaAnimation.setInterpolator(new AccelerateInterpolator());
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mask.setVisibility(View.GONE);
                view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mask.startAnimation(alphaAnimation);
    }

    private class BrowseVpgFromNetAdapter extends PagerAdapter {
        private LayoutInflater mInflater = null;

        public BrowseVpgFromNetAdapter() {
            mInflater = LayoutInflater.from(getActivity());
        }

        @Override
        public int getCount() {
            return imageUrls.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int pos) {

            View view = mInflater.inflate(R.layout.layout_view_detail, null, false);
            final PhotoView photoView = (PhotoView) view.findViewById(R.id.image_detail);
            final PhotoView thumbnailView = (PhotoView) view.findViewById(R.id.image_thumbnail);
            final View progressBar = view.findViewById(R.id.avloading);
            progressBar.setVisibility(View.VISIBLE);
            final String imgUrl = imageUrls.get(pos);
            // final String thumbnailImageUrl = Utils.replaceUrl(imgUrl, "400_");
            final String thumbnailImageUrl = imgUrl;
            if (Utils.isImageCacheAvailable(imgUrl)) {//full image cache is available
                if (pos == position) {//only animation in where you click
                    photoView.animateFrom(info);
                }
                progressBar.setVisibility(View.GONE);
                thumbnailView.setVisibility(View.GONE);
                Utils.displayImageWithCache(imgUrl, photoView, null);
            } else {

                if (Utils.isImageCacheAvailable(thumbnailImageUrl)) {//if we had thumbnail image cache available
                    thumbnailView.setVisibility(View.VISIBLE);
                    thumbnailView.animateFrom(info);//animate from pre layout photoView
                }

                Utils.displayImageWithCache(thumbnailImageUrl, thumbnailView, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        Utils.displayImageWithCache(imgUrl, photoView, new SimpleImageLoadingListener() {
                            @Override
                            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                progressBar.setVisibility(View.GONE);
                                thumbnailView.setVisibility(View.GONE);
                                //once we load full image,we need animate from thumbnail view
                                photoView.animateFrom(thumbnailView.getInfo());
                            }

                            @Override
                            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                                super.onLoadingFailed(imageUri, view, failReason);
                                progressBar.setVisibility(View.GONE);
                                if (failReason.getType() == FailReason.FailType.NETWORK_DENIED) {
                                    Utils.makeCustomToast(getContext(), "网络异常，加载失败", Toast.LENGTH_SHORT);
                                } else {
                                    Utils.makeCustomToast(getContext(), "图片加载失败,请稍后重试！", Toast.LENGTH_SHORT);
                                }
                            }

                            @Override
                            public void onLoadingCancelled(String imageUri, View view) {
                                super.onLoadingCancelled(imageUri, view);
                                progressBar.setVisibility(View.GONE);
                            }
                        });
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        super.onLoadingFailed(imageUri, view, failReason);
                        progressBar.setVisibility(View.GONE);
                        if (failReason.getType() == FailReason.FailType.NETWORK_DENIED) {
                            Utils.makeCustomToast(getContext(), "网络异常，加载失败", Toast.LENGTH_SHORT);
                        } else {
                            Utils.makeCustomToast(getContext(), "图片加载失败,请稍后重试！", Toast.LENGTH_SHORT);
                        }
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {
                        super.onLoadingCancelled(imageUri, view);
                        progressBar.setVisibility(View.GONE);
                    }
                });
            }

            //force to get focal point,to listen key listener
            photoView.setFocusableInTouchMode(true);
            photoView.requestFocus();
            photoView.setOnKeyListener(pressKeyListener);//add key listener to listen back press
            photoView.setOnClickListener(onClickListener);
            photoView.setTag(pos);
            photoView.enable();
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    private class BrowseVpgFromFileAdapter extends PagerAdapter {
        private LayoutInflater mInflater = null;

        public BrowseVpgFromFileAdapter() {
            mInflater = LayoutInflater.from(getActivity());
        }

        @Override
        public int getCount() {
            return imageUrls.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int pos) {

            View view = mInflater.inflate(R.layout.layout_view_detail, null, false);
            final PhotoView photoView = (PhotoView) view.findViewById(R.id.image_detail);
            final PhotoView thumbnailView = (PhotoView) view.findViewById(R.id.image_thumbnail);
            final View progressBar = view.findViewById(R.id.avloading);
            progressBar.setVisibility(View.VISIBLE);
           final String imgUrl = "file://" + imageUrls.get(pos);
            // final String imgUrl =  imageUrls.get(pos);
            // final String thumbnailImageUrl = Utils.replaceUrl(imgUrl, "400_");
            final String thumbnailImageUrl = imgUrl;
            if (Utils.isImageCacheAvailable(imgUrl)) {//full image cache is available
                if (pos == position) {//only animation in where you click
                    photoView.animateFrom(info);
                }
                progressBar.setVisibility(View.GONE);
                thumbnailView.setVisibility(View.GONE);
                Utils.displayImageWithCache(imgUrl, photoView, null);
            } else {

                if (Utils.isImageCacheAvailable(thumbnailImageUrl)) {//if we had thumbnail image cache available
                    thumbnailView.setVisibility(View.VISIBLE);
                    thumbnailView.animateFrom(info);//animate from pre layout photoView
                }

                Utils.displayImageWithCache(thumbnailImageUrl, thumbnailView, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        Utils.displayImageWithCache(imgUrl, photoView, new SimpleImageLoadingListener() {
                            @Override
                            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                progressBar.setVisibility(View.GONE);
                                thumbnailView.setVisibility(View.GONE);
                                //once we load full image,we need animate from thumbnail view
                                photoView.animateFrom(thumbnailView.getInfo());
                            }

                            @Override
                            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                                super.onLoadingFailed(imageUri, view, failReason);
                                progressBar.setVisibility(View.GONE);
                                if (failReason.getType() == FailReason.FailType.NETWORK_DENIED) {
                                    Utils.makeCustomToast(getContext(), "网络异常，加载失败", Toast.LENGTH_SHORT);
                                } else {
                                    Utils.makeCustomToast(getContext(), "图片加载失败,请稍后重试！", Toast.LENGTH_SHORT);
                                }
                            }

                            @Override
                            public void onLoadingCancelled(String imageUri, View view) {
                                super.onLoadingCancelled(imageUri, view);
                                progressBar.setVisibility(View.GONE);
                            }
                        });
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        super.onLoadingFailed(imageUri, view, failReason);
                        progressBar.setVisibility(View.GONE);
                        if (failReason.getType() == FailReason.FailType.NETWORK_DENIED) {
                            Utils.makeCustomToast(getContext(), "网络异常，加载失败", Toast.LENGTH_SHORT);
                        } else {
                            Utils.makeCustomToast(getContext(), "图片加载失败,请稍后重试！", Toast.LENGTH_SHORT);
                        }
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {
                        super.onLoadingCancelled(imageUri, view);
                        progressBar.setVisibility(View.GONE);
                    }
                });
            }

            //force to get focal point,to listen key listener
            photoView.setFocusableInTouchMode(true);
            photoView.requestFocus();
            photoView.setOnKeyListener(pressKeyListener);//add key listener to listen back press
            photoView.setOnClickListener(onClickListener);
            photoView.setTag(pos);
            photoView.enable();
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
}
